package com.smz.service.impl;


import com.smz.entity.Functions;
import com.smz.entity.Role;
import com.smz.entity.User;
import com.smz.service.FunctionsService;
import com.smz.service.RoleService;
import com.smz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private FunctionsService functionsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectUserByName(username);
        if (user==null){
            throw new UsernameNotFoundException("用户名找不到");
        }
        List<Role> roles = roleService.selectAllRoleByName(username);

        List<Functions> functions = functionsService.selectFunctionsByName(username);

        StringBuilder str = new StringBuilder();

        roles.forEach(role -> str.append("ROLE_"+role.getName()+","));
        functions.forEach(function -> str.append(function.getName()+"."));

        str.deleteCharAt(str.length()-1);

        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(str.toString()));
    }
}
